﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.BLL;
using WXYW.DAL;
using System.Web.Configuration;

namespace WXYW
{
    public partial class BJXXNeedApprove : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindForms();
            }
        }

        private void BindForms()
        {
            ApplicationProductService service = new ApplicationProductService();
            ApplicationProduct product = service.GetApplicationProductByID(long.Parse(Request.QueryString[Constants.QUERYSTR_PRODUCT_ID]));
            if (!product.ApplicationFormReference.IsLoaded)
            {
                product.ApplicationFormReference.Load();
            }
            if (!product.ApplicationForm.UserReference.IsLoaded)
            {
                product.ApplicationForm.UserReference.Load();
            }
            if (!product.ApplicationForm.ApplicationPicture.IsLoaded)
            {
                product.ApplicationForm.ApplicationPicture.Load();
            }
            if (!product.ProductTypeReference.IsLoaded)
            {
                product.ProductTypeReference.Load();
            }
            if (!product.ProblemTypeReference.IsLoaded)
            {
                product.ProblemTypeReference.Load();
            }
            

            contactLabel.Text = product.ApplicationForm.User.ContactPerson;
            companyLabel.Text = product.ApplicationForm.User.FullName;
            phoneNumberLabel.Text = product.ApplicationForm.User.UserPhone;
            cellPhoneLabel.Text = product.ApplicationForm.User.UserMobilePhone;
            faxLabel.Text = product.ApplicationForm.User.UserFax;
            addressLabel.Text = product.ApplicationForm.User.UserAddress;
            emailLabel.Text = product.ApplicationForm.User.UserEmail;
            emailTxtBox.Text = product.ApplicationForm.User.UserEmail;
            agentLabel.Text = product.ApplicationForm.ProviderName;
            Label1.Text = product.ApplicationForm.ApplicationDateTime.Value.ToString("yyyy-MM-dd");
            Label2.Text = product.DealWithDateTime.HasValue ? product.DealWithDateTime.Value.ToString("yyyy-MM-dd") : "";
            applierLbl.Text = product.ApplicationForm.User.ContactPerson;
            customerPhoneTxtBox.Text = product.ApplicationForm.User.UserMobilePhone;
            declineSMS2CustomerPhoneTxtBox.Text = product.ApplicationForm.User.UserMobilePhone;
            declineEmailTxtBox.Text = product.ApplicationForm.User.UserEmail;
            if (product.BJSQYBService.HasValue && product.BJSQYBService.Value)
            {
                ybLbl.Text = "是";
            }
            else
            {
                ybLbl.Text = "否";
            }
            //
            UserService userservice = new UserService();
            if (product.ApplicationForm.AgentID.HasValue)
            {
                User agent = userservice.GetUserByID(product.ApplicationForm.AgentID.Value);
                Label3.Text = agent.ContactPerson;
                Label4.Text = agent.UserMobilePhone + ";" + agent.UserPhone;
                applierPhoneTxtBox.Text = agent.UserMobilePhone;
                declineSMS2ApplierPhoneTxtBox.Text = agent.UserMobilePhone;
            }
            else
            {
                applierPhoneTxtBox.Text = product.ApplicationForm.User.UserMobilePhone;
                declineSMS2ApplierPhoneTxtBox.Text = product.ApplicationForm.User.UserMobilePhone;
            }

            if (product.ApplicationForm.ApplicationType.Equals("BB"))
            {
                applyTypeLabel.Text = "备件先行";
            }
            else if (product.ApplicationForm.ApplicationType.Equals("BD"))
            {
                applyTypeLabel.Text = "DOA";
            }
            emailNoticeTxtBox.Text = string.Format(WebConfigurationManager.AppSettings["BJXXEmailNoticeBody"], product.ApplicationForm.User.ContactPerson, product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text, product.ApplicationForm.RunningNumber);
            SMS2ApplierTxtBox.Text = string.Format(WebConfigurationManager.AppSettings["BJXXSMS2ApplierBody"], product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text, product.ApplicationForm.ApplicationCode);
            SMSToCustomerTxtBox.Text = string.Format(WebConfigurationManager.AppSettings["BJXXSMS2CustomerBody"], product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text, product.ApplicationForm.RunningNumber);
            SMSToSaleTxtBox.Text = string.Format(WebConfigurationManager.AppSettings["BJXXSMS2SaleBody"], product.ApplicationForm.User.CompanyName, product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text, product.ApplicationForm.RunningNumber);

            declineEmailContentTxtBox.Text = string.Format(WebConfigurationManager.AppSettings["BJXXDeclineEmailNoticeBody"], product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text);
            declineSMS2ApplierContentTxtBox.Text = string.Format(WebConfigurationManager.AppSettings["BJXXDeclineSMS2ApplierBody"], product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text);
            declineSMS2CustomerContentTxtBox.Text = string.Format(WebConfigurationManager.AppSettings["BJXXDeclineSMS2CustomerBody"], product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text);
            declineSMS2SaleContentTxtBox.Text = string.Format(WebConfigurationManager.AppSettings["BJXXDeclineSMS2SaleBody"], product.ApplicationForm.User.CompanyName, product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text);

            shxxLbl.Text = product.ApplicationForm.BJXXSHAddress;
            //
            requireDisPLabel.Text = product.BJSQNeedComment;
            runningNumberLabel.Text = product.ApplicationForm.RunningNumber;
            //clientNameLabel.Text = product.ApplicationForm.User.UserName;
            //spcodeLabel.Text = product.SPCode;
            productTypeLabel.Text = product.ProductType.ProductTypeName;
            serialNOLinkButton.Text = product.ProductSerialNumber;
            //applyTimeLabel.Text = product.ApplicationForm.ApplicationDateTime.Value.ToString("yyyy-MM-dd");
            buyTimeLabel.Text = product.ProductPurchaseDateTime.Value.ToString("yyyy-MM-dd");
            statusLabel.Text = product.Status;
            //repairTupeLabel.Text = product.ProductRepairType;
            repairTypeDDL.SelectedValue = product.ProductRepairType;
            problemDescriptionLabel.Text = product.ProductProblemDescription;
            problemTypeLabel.Text = product.ProblemType.Name;
            accessoryLabel.Text = product.ProductAppearance;
            versionNumberLabel.Text = product.ProductVersionNumber;
            // pictures            
            List<ApplicationPicture> list = product.ApplicationForm.ApplicationPicture.ToList();
            Table table = new Table();
            table.Rows.Add(new TableRow());
            table.Rows.Add(new TableRow());
            foreach (ApplicationPicture picture in list)
            {
                string docType = GetDocType(picture.PictureNameOnServer);
                TableCell celllImage = new TableCell();
                Image imageControl = new Image();
                imageControl.Height = 100;
                if (docType.ToLower() != "jpg" && docType.ToLower() != "bmp" && docType.ToLower() != "gif" && docType.ToLower() != "png")
                {
                    imageControl.ImageUrl = "image/" + "document.png";
                    imageControl.Attributes.Add("OnClick", "window.open('Picture/" + picture.PictureNameOnServer + "')");
                }
                else
                {
                    imageControl.ImageUrl = "Picture/" + picture.PictureNameOnServer;
                    imageControl.Attributes.Add("OnClick", "window.open('ImageDetail.aspx?Name=" + picture.PictureNameOnServer + "')");
                }

                celllImage.Controls.Add(imageControl);
                table.Rows[0].Cells.Add(celllImage);

                TableCell cellName = new TableCell();
                Label label = new Label();
                label.Text = picture.PictureName;
                cellName.Controls.Add(label);
                table.Rows[1].Cells.Add(cellName);
            }
            picturePanel.Controls.Add(table);

            // for buttons
            if (product.BJXXDealResult.HasValue)
            {
                approveLinkButton.Enabled = false;
                declineLinkButton.Enabled = false;
                //sendLinkButton.Enabled = true;
            }
            else
            {
                approveLinkButton.Enabled = true;
                declineLinkButton.Enabled = true;
                //sendLinkButton.Enabled = false;
            }
        }

        private string GetDocType(string nameonserver)
        {
            if (!string.IsNullOrEmpty(nameonserver))
            {
                string[] nametype = nameonserver.Split('.');
                return nametype[1];
            }
            else
            {
                return string.Empty;
            }
        }

        protected void approveLinkButton_Click(object sender, EventArgs e)
        {
            ModalPopupExtender2.Show();
        }

        protected void approveButton_Click(object sender, EventArgs e)
        {
            ApplicationProductService service = new ApplicationProductService();
            ApplicationProduct product = service.GetApplicationProductByID(long.Parse(Request.QueryString[Constants.QUERYSTR_PRODUCT_ID]));
            product.BJXXDealResult = true;
            if (applyTypeLabel.Text.Equals("DOA"))
            {
                product.SPCode = RunningNumberService.GenerateDOACode();
            }
            else
            {
                product.SPCode = RunningNumberService.GenerateBJXXCode();
            }
            product.BJXXApproveComment = approveTextBox.Text;
            product.DealUserID = ContextService.CurrentAccount.UserID;
            product.DealWithDateTime = DateTime.Now;
            product.Status = "已审批-待发货";
            product.ProductRepairType = repairTypeDDL.SelectedValue;

            // update applicationform 
            if (!product.ApplicationFormReference.IsLoaded)
            {
                product.ApplicationFormReference.Load();
            }
            product.ApplicationForm.Status = "已审批-批准";
            product.ApplicationForm.ApplicationCode = product.SPCode;

            service.UpdateProduct(product);
            //BindForms();
            //EmailService.SendEmail(emailLabel.Text, "备件先行审批", string.Format(WebConfigurationManager.AppSettings["BJXXApprove"], companyLabel.Text, productTypeLabel.Text));
            if (isSendEmailChkBox.Checked)
            {
                //EmailService.SendEmail(emailTxtBox.Text.Trim(), "备件先行审批", string.Format(WebConfigurationManager.AppSettings["BJXXEmailNoticeBody"], product.ApplicationForm.User.ContactPerson, product.ApplicationForm.ApplicationDateTime.Value.Month,
                //product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text, product.ApplicationForm.ApplicationCode));

                string[] emails = emailTxtBox.Text.Trim().Split(new char[] { '，', '，', ' ', ';', });
                for (int index = 0; index < emails.Length; index++)
                {
                    EmailService.SendEmail(emails[index], "备件先行审批", string.Format(WebConfigurationManager.AppSettings["BJXXEmailNoticeBody"], product.ApplicationForm.User.ContactPerson, product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text, product.ApplicationForm.ApplicationCode));
                }
            }
            if (isSendSMS2ApplierChkBox.Checked)
            {
                SMSService.SendSMS(string.Format(WebConfigurationManager.AppSettings["BJXXSMS2ApplierBody"], product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text, product.ApplicationForm.ApplicationCode), applierPhoneTxtBox.Text.Trim());
            }
            if (isSendSMS2CustomerChkBox.Checked)
            {
                SMSService.SendSMS(string.Format(WebConfigurationManager.AppSettings["BJXXSMS2CustomerBody"], product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text, product.ApplicationForm.ApplicationCode), customerPhoneTxtBox.Text.Trim());
            }
            if (isSendSMS2SaleChkBox.Checked)
            {
                string[] saleMobilePhone = salePhoneTxtBox.Text.Trim().Split(new char[] { '，', '，', ' ' ,';',});
                for (int index = 0; index < saleMobilePhone.Length; index++)
                {
                    SMSService.SendSMS(string.Format(WebConfigurationManager.AppSettings["BJXXSMS2SaleBody"], product.ApplicationForm.User.CompanyName, product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text, product.ApplicationForm.RunningNumber), saleMobilePhone[index]);
                }
            }
            ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('您已经批准了这个申请');location.href='BJXXListNeedApprove.aspx';", true);
        }

        protected void declineLinkButton_Click(object sender, EventArgs e)
        {
            BackPopupExtender.Show();
        }

        protected void declineButton_Click(object sender, EventArgs e)
        {
            ApplicationProductService service = new ApplicationProductService();
            ApplicationProduct product = service.GetApplicationProductByID(long.Parse(Request.QueryString[Constants.QUERYSTR_PRODUCT_ID]));
            product.DealWithDateTime = DateTime.Now;
            product.BJXXDealResult = false;
            product.BJXXApproveComment = reasonTextBox.Text;
            product.DealUserID = ContextService.CurrentAccount.UserID;
            product.Status = "已审批-未批准";
            product.ProductRepairType = repairTypeDDL.SelectedValue;

            // update applicationform 
            if (!product.ApplicationFormReference.IsLoaded)
            {
                product.ApplicationFormReference.Load();
            }
            product.ApplicationForm.Status = "已审批-未批准";

            service.UpdateProduct(product);
            //BindForms();
            //EmailService.SendEmail(emailLabel.Text, "备件先行审批", string.Format(WebConfigurationManager.AppSettings["BJXXDecline"], companyLabel.Text, productTypeLabel.Text));
            if (declineEmailChxBox.Checked)
            {
                //EmailService.SendEmail(declineEmailTxtBox.Text.Trim(), "备件先行审批", string.Format(WebConfigurationManager.AppSettings["BJXXDeclineEmailNoticeBody"], product.ApplicationForm.ApplicationDateTime.Value.Month,
                //product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text));

                string[] emails = declineEmailTxtBox.Text.Trim().Split(new char[] { '，', '，', ' ', ';', });
                for (int index = 0; index < emails.Length; index++)
                {
                    EmailService.SendEmail(emails[index], "备件先行审批", string.Format(WebConfigurationManager.AppSettings["BJXXDeclineEmailNoticeBody"], product.ApplicationForm.User.ContactPerson, product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text, product.ApplicationForm.ApplicationCode));
                }
            }
            if (declineSMS2ApplierChkBox.Checked)
            {
                SMSService.SendSMS(string.Format(WebConfigurationManager.AppSettings["BJXXDeclineSMS2ApplierBody"], product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text), declineSMS2ApplierPhoneTxtBox.Text.Trim());
            }
            if (declineSMS2CustomerChkBox.Checked)
            {
                SMSService.SendSMS(string.Format(WebConfigurationManager.AppSettings["BJXXDeclineSMS2CustomerBody"], product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text), customerPhoneTxtBox.Text.Trim());
            }
            if (declineSMS2SaleChkBox.Checked)
            {
                string[] saleMobilePhone = declineSMS2SalePhoneTxtbox.Text.Trim().Split(new char[] { '，', '，', ' ', ';', });
                for (int index = 0; index < saleMobilePhone.Length; index++)
                {
                    SMSService.SendSMS(string.Format(WebConfigurationManager.AppSettings["BJXXDeclineSMS2SaleBody"], product.ApplicationForm.User.CompanyName, product.ApplicationForm.ApplicationDateTime.Value.Month,
                product.ApplicationForm.ApplicationDateTime.Value.Day, applyTypeLabel.Text, product.ApplicationForm.RunningNumber), saleMobilePhone[index]);
                }
            }
            ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('您已经拒绝了这个申请');location.href='BJXXListNeedApprove.aspx';", true);
        }

        //protected void sendLinkButton_Click(object sender, EventArgs e)
        //{
        //    Modalpopupextender1.Show();
        //    bodyTextBox.Text = string.Format(WebConfigurationManager.AppSettings["BJXXApprove"], companyLabel.Text, productTypeLabel.Text);
        //}

        //protected void sendButton_Click(object sender, EventArgs e)
        //{
        //    ApplicationProductService service = new ApplicationProductService();
        //    ApplicationProduct product = service.GetApplicationProductByID(long.Parse(Request.QueryString[Constants.QUERYSTR_PRODUCT_ID]));
        //    if (product.BJXXDealResult.Value == true)
        //    {
        //        product.Status = "已审批-待发货";
        //    }
        //    else
        //    {
        //        product.Status = "已审批-未批准";
        //    }
        //    service.UpdateProduct(product);

        //    EmailService.SendEmail(emailLabel.Text, "备件先行审批", bodyTextBox.Text);

        //    Response.Redirect("BJXXListNeedApprove.aspx");
        //}

        protected void uploadButton_Click(object sender, EventArgs e)
        {
            long applicationID = 0;
            string fileType = string.Empty;
            string fileName = string.Empty;
            string fileNameOnServer = string.Empty;
            if (FileUpload1.HasFile)
            {
                fileType = FileUpload1.FileName.Substring(FileUpload1.FileName.LastIndexOf("."));
                fileName = FileUpload1.FileName;
                fileNameOnServer = Guid.NewGuid() + fileType;
                FileUpload1.SaveAs(Server.MapPath("Picture/" + fileNameOnServer));
            }

            ApplicationProductService productservice = new ApplicationProductService();
            ApplicationProduct product = productservice.GetApplicationProductByID(long.Parse(Request.QueryString[Constants.QUERYSTR_PRODUCT_ID]));
            if (!product.ApplicationFormReference.IsLoaded)
            {
                product.ApplicationFormReference.Load();
            }
            applicationID = product.ApplicationForm.ApplicationID;

            if (applicationID > 0)
            {
                ApplicationService service = new ApplicationService();
                ApplicationForm form = service.GetApplicationFormByID(applicationID);
                ApplicationPicture picture = new ApplicationPicture
                {
                    PictureName = fileName,
                    PictureNameOnServer = fileNameOnServer,
                    Type = (int)PictureType.ConfirmProduct,
                    UploadPerson = ContextService.CurrentAccount.UserID
                };
                form.ApplicationPicture.Add(picture);
                service.UpdateApplication(form);

                Response.Redirect(Request.Url.ToString());
            }
        }

        protected void serialNOLinkButton_Click(object sender, EventArgs e)
        {
            LinkButton serialNOLinkButton = sender as LinkButton;
            ProductService service = new ProductService();
            ProductInfo pi = service.GetProductInfoBySerialNO(serialNOLinkButton.Text);
            if (pi != null)
            {
                serialNOLabel.Text = pi.SerialNO;
                saleUserLabel.Text = pi.JXSName;
                endtimeLabel.Text = pi.EndTime.HasValue ? pi.EndTime.Value.ToString("yyyy-MM-dd") : "";
                toLabel.Text = pi.SellTime.HasValue ? pi.SellTime.Value.ToString("yyyy-MM-dd") : "";
                informationLabel.Visible = false;
            }
            else
            {
                informationLabel.Visible = true;
                informationLabel.Text = "没有找到相关信息！";
            }

            notificationModalPopupExtender.Show();
        }
    }
}
